package com.ukao.steward.printer;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ukao.steward.R;
import com.ukao.steward.bean.ReceiptBean;
import com.ukao.steward.bean.StringBean;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.DecimalUtil;
import com.ukao.steward.util.L;
import com.ukao.steward.util.MyDateUtils;
import com.ukao.steward.util.T;
import com.ukao.steward.util.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import zpSDK.zpSDK.zpBluetoothPrinter;

import static cn.jpush.android.api.JPushInterface.a.t;
import static com.ukao.steward.R.id.storeName;


/**
 * Created by ukaodev on 2018/3/31.
 */

public class BluetoothPrintHelper {

    /**
     打印文字
     *
     * @param x
     *            起始横坐标
     * @param y
     *            起始纵坐标
     * @param width
     *            文本框宽度
     * @param height
     *            文本框高度
     * @param str
     *            字符串
     * @param fontsize
     *            字体大小 1：16点阵；2：24点阵；3：32点阵；4：24点阵放大一倍；5：32点阵放大一倍
     *            6：24点阵放大两倍；7：32点阵放大两倍；其他：24点阵
     * @param rotate
     *            旋转角度 0：不旋转；1：90度；2：180°；3:270°
     * @param bold
     *            是否粗体 0：取消；1：设置
     * @param underline
     *            是有有下划线 false:没有；true：有
     * @param reverse
     *            是否反白 false：不反白；true：反白
     *
     */

    private static  String mBDAddress;
    private static  int   height=0;
    private static  int   addheight=30;
    private static  int   leftX=330;

    public static   void receiptReceipt(FragmentActivity _mActivity,  ReceiptBean printInfo){
        mBDAddress="";
        if (!ListBluetoothDevice(_mActivity)&&CheckUtils.isEmpty(mBDAddress)){
            T.show("该设备未连接蓝牙打印机");

            return;
        }

        try {

            List<StringBean> mClothlist = null;
            if (!CheckUtils.isEmpty(printInfo.getProPriceDesc())){
                Gson mGson = new Gson();
                mClothlist = mGson.fromJson(printInfo.getProPriceDesc(),
                        new TypeToken<List<StringBean>>() {
                        }.getType());
            }
            zpBluetoothPrinter zpSDK=new zpBluetoothPrinter(Utils.getContext());
            zpSDK.connect(mBDAddress);
            int  pageHeight=getHeight(printInfo,mClothlist);
            L.i("height"+pageHeight);
            zpSDK.pageSetup(850, pageHeight);
            /*/*店名  与单号*/
            height=0;
          String  storeName=printInfo.getStoreName();
            if (!CheckUtils.isEmpty(storeName)){
                zpSDK.drawText(190,addaddheight(addheight), storeName, 4, 0, 0, false, false);

            }

            zpSDK.drawText(210,CheckUtils.isEmpty(storeName)?addaddheight(addheight):addaddheight(60), printInfo.getOrderNo(), 2, 0, 0, false, false);

//            /*设置二维码*/
            zpSDK.drawQrCode(210, addaddheight(50) ,printInfo.getOrderNo(), 0, 3, 10);

            List<ReceiptBean.OrderProductListBean> mProductList=printInfo.getOrderProductList();


            /*入库*/
            if (!CheckUtils.isEmpty(printInfo.getRecoredTime())) {
                String storagtext =  "入库："+MyDateUtils.formatDateCustom(printInfo.getRecoredTime(), "MM-dd HH:mm:ss");
                String cloCount = printInfo.getClothCnt() + printInfo.getAnnexCnt();
                zpSDK.drawText(2, addaddheight(180), storagtext, 2, 0, 0, false, false);
                zpSDK.drawText(leftX, addaddheight(0), cloCount, 2, 0, 0, false, false);
            }

            zpSDK.drawText(2,CheckUtils.isEmpty(printInfo.getRecoredTime())? addaddheight(150):addaddheight(30), "-----------------------------------------------", 2, 0, 0, false, false);
              /*衣物列表*/
            if (!CheckUtils.isEmpty(mProductList)) {

                zpSDK.drawText(2,addaddheight(30), "入库衣物清单：", 2, 0, 0, false, false);
                Gson mGson = new Gson();
                for (int j = 0; j < mProductList.size(); j++) {

                    ReceiptBean.OrderProductListBean orderProductListBean = mProductList.get(j);
//                    String color = "";
//                    if (!CheckUtils.isEmpty(orderProductListBean.getColorDesc())) {  /*/*瑕疵*/
//                        List<StringBean> mColorDesclist = mGson.fromJson(orderProductListBean.getColorDesc(),
//                                new TypeToken<List<StringBean>>() {
//                                }.getType());
//                        StringBuffer mColorBuffer1 = new StringBuffer();
//                        for (int i = 0; i < mColorDesclist.size(); i++) {
//                            if (i != mColorDesclist.size() - 1) {
//                                mColorBuffer1.append(mColorDesclist.get(i).getName() + "/");
//                            } else {
//                                mColorBuffer1.append(mColorDesclist.get(i).getName());
//                            }
//
//
//                        }
//                        color = mColorBuffer1.toString();
//                    }

//                    String strflawDesc = "";
//                    if (!CheckUtils.isEmpty(orderProductListBean.getFlawDesc())) {  /*/*瑕疵*/
//                        List<StringBean> mflawDesclist = mGson.fromJson(orderProductListBean.getFlawDesc(),
//                                new TypeToken<List<StringBean>>() {
//                                }.getType());
//                        StringBuffer mflawBuffer = new StringBuffer();
//                        for (int i = 0; i < mflawDesclist.size(); i++) {
//                            if (i != mflawDesclist.size() - 1) {
//                                mflawBuffer.append(mflawDesclist.get(i).getName() + "/");
//                            } else {
//                                mflawBuffer.append(mflawDesclist.get(i).getName());
//                            }
//
//
//                        }
//                        strflawDesc = mflawBuffer.toString();
//                    }

                    String    productName=orderProductListBean.getProductName() + " " + orderProductListBean.getScanCode();
                    zpSDK.drawText(2, addaddheight(addheight), productName, 2, 0, 0, false, false);
                    String[] piceText = new String[2];
                    piceText[0]="￥" + CheckUtils.isEmptyNumber(orderProductListBean.getServiceAmt()) + "*" + orderProductListBean.getDiscount() + "%" ;
                    piceText[1]="￥"+CheckUtils.isEmptyNumber(orderProductListBean.getSubtotal());
                    zpSDK.drawText(2, addaddheight(addheight),  piceText[0], 2, 0, 0, false, false);
                    zpSDK.drawText(leftX, addaddheight(0), piceText[1], 2, 0, 0, false, false);

//                    if (!CheckUtils.isEmpty(color)&&!CheckUtils.isEmpty(strflawDesc)){
//                        color=color+"/"+strflawDesc;
//                    }else if (CheckUtils.isEmpty(color)&&!CheckUtils.isEmpty(strflawDesc)){
//                        color=strflawDesc;
//                    }




                }
            }
            String  orderTotalAmount = "0.00";
            if (!CheckUtils.isEmpty(mClothlist)&&CheckUtils.isEmpty(mProductList)){

                zpSDK.drawText(2, addaddheight(addheight), "下单衣物清单：", 2, 0, 0, false, false);
                for (StringBean stringBean : mClothlist) {
                    String    productName=stringBean.getName() ;
                    String[] piceText = new String[2];
                    String discount = stringBean.getDiscount() == 0 || stringBean.getDiscount() == 100 ? "" : "*"+stringBean.getDiscount() + "%";
                    String unitPrice = CheckUtils.isEmptyNumber(stringBean.getPrice());
                    String cnts=stringBean.getCnts();
                    String totalAmount ="";
                    if (!CheckUtils.isEmpty(discount)){
                        totalAmount = DecimalUtil.multiply(cnts, DecimalUtil.multiply(unitPrice, CheckUtils.isEmptyNumber(stringBean.getDiscount())));

                    }else{
                        totalAmount=DecimalUtil.multiply(cnts,unitPrice);
                    }
                    orderTotalAmount= DecimalUtil.add(orderTotalAmount, totalAmount);
                    piceText[0]="￥" +unitPrice;
                    piceText[1]="￥"+totalAmount;
                  int   intDiscount=stringBean.getDiscount()==0?100:stringBean.getDiscount();
                    String  striscount="*" + intDiscount + "%";
                    zpSDK.drawText(2,addaddheight(addheight), productName+piceText[0]+striscount , 2, 0, 0, false, false);
                    zpSDK.drawText(leftX+100, height,  piceText[1], 2, 0, 0, false, false);

                }



            }


            if (!CheckUtils.isEmpty(mProductList)||!CheckUtils.isEmpty(mClothlist)){
                cutoffs(zpSDK);
            }

            String cloTotalAmount ;
            if (!CheckUtils.isNull(printInfo.getValuationPrice()) ||CheckUtils.isEmptyInterExist(printInfo.getOrderPrice()) ||!CheckUtils.isNull(printInfo.getModifyPrice())) {  //下单模式 1.预约模式 2.下单支付模式
                /*计价*/
                if (!CheckUtils.isNull(printInfo.getValuationPrice())) {
                    cloTotalAmount=CheckUtils.isEmptyNumber(printInfo.getValuationPrice());
                } else {
                    int  modifyPrice=CheckUtils.isNull(printInfo.getModifyPrice())?0:printInfo.getModifyPrice();
                    int orderPrice = CheckUtils.isNull(printInfo.getOrderPrice()) ? 0 : printInfo.getOrderPrice();
                    int totalPrice = orderPrice != 0 ? printInfo.getOrderPrice() : modifyPrice;
                    cloTotalAmount = CheckUtils.isEmptyNumber(totalPrice);

                }


            } else {
                cloTotalAmount=orderTotalAmount;
            }
            zpSDK.drawText(leftX,addaddheight(addheight), "衣物总额："+cloTotalAmount, 2, 0, 0, false, false);

            if (printInfo.getCouponAmt()!=0){/*优惠卷 */

                zpSDK.drawText(leftX,addaddheight(addheight), "优惠卷："+CheckUtils.isEmptyNumber(printInfo.getCouponAmt()), 2, 0, 0, false, false);
            }
            if (printInfo.getIsModifyPrice()){/*修改金额 */

                zpSDK.drawText(leftX,addaddheight(addheight), "修改金额："+CheckUtils.isEmptyNumber(printInfo.getModifyPrice()), 2, 0, 0, false, false);
            }
            int   takesEndFee=printInfo.getSendCarriage()+printInfo.getTakeCarriage();
            if (takesEndFee!=0){  /*取送费*/
                zpSDK.drawText(leftX,addaddheight(addheight), "取送费："+CheckUtils.isEmptyNumber(takesEndFee), 2, 0, 0, false, false);
            }


            if (printInfo.getPayStatus()){/* 已支付金额*/
                zpSDK.drawText(leftX,addaddheight(addheight), "已付金额："+CheckUtils.isEmptyNumber(printInfo.getPaidPrice()), 2, 0, 0, false, false);

            }
            zpSDK.drawText(leftX, addaddheight(addheight), "付款状态："+printInfo.getPayStatusText(), 2, 0, 0, false, false);
            cutoffs(zpSDK);

            /*客户备注*/
            if (!CheckUtils.isEmpty( printInfo.getUserRemark())){
                zpSDK.drawText(2, addaddheight(addheight), "客户备注："+printInfo.getUserRemark(), 2, 0, 0, false, false);

            }else{
                zpSDK.drawText(2, addaddheight(addheight), "客户备注：无", 2, 0, 0, false, false);
            }
            cutoffs(zpSDK);
            String  userName="";
            if (!CheckUtils.isEmpty(printInfo.getUserName())){
                userName="  "+printInfo.getUserName();
            }
            if (!CheckUtils.isEmpty(printInfo.getUserPhone())){
                userName=printInfo.getUserPhone()+userName;
            }
            zpSDK.drawText(2, addaddheight(addheight), "客户："+userName, 2, 0, 0, false, false);
            zpSDK.drawText(2, addaddheight(addheight), "卡号："+printInfo.getUserCardNo(), 2, 0, 0, false, false);
            String  discount="";
            if (printInfo.getDiscountType()){
                discount="多折扣";
            }else{
                discount=printInfo.getDiscount()+"%";
            }

            zpSDK.drawText(2, addaddheight(addheight),"折扣："+discount+"%"+"  余额：￥"+CheckUtils.isEmptyNumber(printInfo.getUserBalance()),2, 0, 0, false, false);
            if (!CheckUtils.isEmpty(printInfo.getTakeAddress())){

                zpSDK.drawText(2, addaddheight(addheight),printInfo.getTakeAddress(), 2, 0, 0, false, false);

            }
           cutoffs(zpSDK);
            if (!CheckUtils.isEmpty(printInfo.getWxCode())){
                zpSDK.drawText(2, addaddheight(addheight),"微信号："+printInfo.getWxCode(), 2, 0, 0, false, false);

            }
            if (!CheckUtils.isEmpty(printInfo.getServiceTel())){
                zpSDK.drawText(2, addaddheight(addheight),"客服电话："+printInfo.getServiceTel(), 2, 0, 0, false, false);

            }
            zpSDK.drawText(2, addaddheight(addheight),"打印时间："+MyDateUtils.getDateTime(), 2, 0, 0, false, false);

            zpSDK.print(0, 0);

            zpSDK.disconnect();


        }catch (Exception e){

                T.show("打印出错");
        }


    }

    public  static boolean ListBluetoothDevice(FragmentActivity _mActivity)
    {
        BluetoothAdapter     myBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
        if(myBluetoothAdapter==null)
            return false;

        /**
         * 判断蓝牙是否打开
         */
        if(!myBluetoothAdapter.isEnabled())
        {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            _mActivity.startActivityForResult(enableBtIntent, 2);
        }

        Set<BluetoothDevice> pairedDevices = myBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() == 0){return  false;}
        for (BluetoothDevice device : pairedDevices)
        {
           mBDAddress=device.getAddress();

        }


        L.i("mBDAddress="+mBDAddress);
        return true;
    }


    public static int getHeight(ReceiptBean printInfo  , List<StringBean> mClothlist) {

            /*/*店名  与单号*/
        height=0;
        if (!CheckUtils.isEmpty(printInfo.getStoreName())) {
            addaddheight(addheight);
        }
        addaddheight(addheight);
        addaddheight(50);

        List<ReceiptBean.OrderProductListBean> mProductList = printInfo.getOrderProductList();

        if (!CheckUtils.isEmpty(printInfo.getProPriceDesc())) {

        }
            /*入库*/
        if (!CheckUtils.isEmpty(printInfo.getRecoredTime())) {
            addaddheight(150);

        } else {
            addaddheight(30);
        }
              /*衣物列表*/
        if (!CheckUtils.isEmpty(mProductList)) {
            addaddheight(30);
            for (int j = 0; j < mProductList.size(); j++) {
                addaddheight(addheight);
                addaddheight(addheight);

            }
        }

        if (!CheckUtils.isEmpty(mClothlist) && CheckUtils.isEmpty(mProductList)) {
            for (StringBean stringBean : mClothlist) {
                addaddheight(addheight);
                addaddheight(addheight);
            }


        }



        addaddheight(addheight);
        if (printInfo.getCouponAmt() != 0) {/*优惠卷 */

            addaddheight(addheight);
        }
        if (printInfo.getIsModifyPrice()) {/*修改金额 */

            addaddheight(addheight);
        }
        int takesEndFee = printInfo.getSendCarriage() + printInfo.getTakeCarriage();
        if (takesEndFee != 0) {  /*取送费*/
            addaddheight(addheight);
        }

        if (printInfo.getPayStatus()) {/* 已支付金额*/
            addaddheight(addheight);

        }
        addaddheight(addheight);
        addaddheight(addheight);

            /*客户备注*/
        if (!CheckUtils.isEmpty(printInfo.getUserRemark())) {
            addaddheight(addheight);

        } else {
            addaddheight(addheight);
        }
        addaddheight(addheight);
        String userName = "";
        if (!CheckUtils.isEmpty(printInfo.getUserName())) {
            userName = "  " + printInfo.getUserName();
        }
        if (!CheckUtils.isEmpty(printInfo.getUserPhone())) {
            userName = printInfo.getUserPhone() + userName;
        }
        addaddheight(addheight);
        addaddheight(addheight);
        String discount = "";
        if (printInfo.getDiscountType()) {
            discount = "多折扣";
        } else {
            discount = printInfo.getDiscount() + "%";
        }

        addaddheight(addheight);
        if (!CheckUtils.isEmpty(printInfo.getTakeAddress())) {

            addaddheight(addheight);

        }
        addaddheight(addheight);
        if (!CheckUtils.isEmpty(printInfo.getWxCode())) {
            addaddheight(addheight);

        }
        if (!CheckUtils.isEmpty(printInfo.getServiceTel())) {
            addaddheight(addheight);

        }
        addaddheight(addheight);
        L.i("addaddheight"+height);
        return   height+260;
    }

    public  static void    cutoffs(zpBluetoothPrinter zpSDK){


        zpSDK.drawText(2, addaddheight(30), "-----------------------------------------------", 2, 0, 0, false, false);

    }


    public  static int     addaddheight( int  addheight ){
        height=height+addheight;


    return  height;
    }

}
